﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using MayhemCore;
using System.ComponentModel;
using MayhemWpf.ModuleTypes;
using System.Threading;
using MayhemWpf.UserControls;
using ComputerMayhem.Wpf;

namespace ComputerMayhem.Events
{
    [DataContract]
    [MayhemModule("Clock", "Trig at a specfic time everyday")]
    public class Clock : EventBase, IWpfConfigurable
    {
        BackgroundWorker _bw;

        private bool triggered = false;

        [DataMember]
        private int hour;

        [DataMember]
        private int minute;

        protected override void OnLoadDefaults()
        {
            hour = 12;
            minute = 0;
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                DateTime currentTime = DateTime.Now;
                bool trigger = currentTime.Hour == hour && currentTime.Minute == minute;
                if (trigger && !triggered)
                {
                    Trigger();
                }
                else if (!trigger)
                {
                    ResetTrigger();
                }
                Thread.Sleep(1000 * 60);
            }
        }

        private void ResetTrigger()
        {
            triggered = false;
        }

        protected override void OnEnabling(EnablingEventArgs e)
        {
            _bw = new BackgroundWorker() { WorkerSupportsCancellation = true };
            _bw.DoWork += bw_DoWork;
            _bw.RunWorkerAsync();
        }

        protected override void OnDisabled(DisabledEventArgs e)
        {
            _bw.CancelAsync();
            _bw.DoWork += bw_DoWork;
            ResetTrigger();
        }

        public WpfConfiguration ConfigurationControl
        {
            get
            {
                return new ClockConfig(hour, minute);
            }
        }

        public void OnSaved(WpfConfiguration configurationControl)
        {
            ClockConfig config = configurationControl as ClockConfig;
            hour = config.Hour;
            minute = config.Minute;

        }

        public string GetConfigString()
        {
            return "At " + hour + ":" + minute + ".";
        }
    }
}
